var config = require('../../utils/config');
var util = require('../../utils/util');
var API_URL = config.API_URL;
var page, loading;
var app = getApp();
let getAddress = that => {
    if (loading) {
        return
    }
    loading = true;
    util.PRL(API_URL.address_list, { page: page })
        .then(res => {
            console.log(res);
            var address;
            var data = res.data.data.data;
            if (page == 1) {
                address = [];
            } else {
                address = that.data.address;
            }
            address = address.concat(data);
            that.setData({
                address: address
            })
            if (data.length != 0) {
                page++
            }
            loading = false;
            my.stopPullDownRefresh()
        }).catch(res => {
            console.log(res);
            loading = false;
            my.stopPullDownRefresh();
        })
}
Page({
    data: {},
    onLoad: function (options) {
        // 页面初始化 options为页面跳转所带来的参数
        loading = false;
        page = 1;
        getAddress(this);
    },
    onReady: function () {
        // 页面渲染完成
    },
    onShow: function () {
        // 页面显示
    },
    onHide: function () {
        // 页面隐藏
    },
    onUnload: function () {
        // 页面关闭
    },
    onPullDownRefresh: function () {
        page = 1;
        loading = false;
        getAddress(this);
    },
    onReachBottom: function () {
        getAddress(this);
    },
    add: function (e) {
        var id = e.currentTarget.dataset.id;
        var index = e.currentTarget.dataset.index;
        var address = this.data.address;
        console.log(`id是${id},index是${index},address是{{address}}`)
        if (id) {
            app.globalData.address = address[index];
        } else {
            app.globalData.address = null;
            id = 0;
        }
        my.redirectTo({
            url: '/pages/address/add/add?id=' + id,
        })
    },
    // 删除
    del: function (e) {
        var id = e.currentTarget.dataset.id;
        var index = e.currentTarget.dataset.index;
        console.log(e)
        var that = this;
        var addrData = that.data.address;
        util.PRL(API_URL.del_address, { address_id: id })
            .then(res => {
                my.showToast({
                    content: '删除成功', // 文字内容
                    success: (res) => {
                        addrData.splice(index, 1);
                        that.setData({
                            address: addrData
                        })
                    },
                    fail: (res) => {
                        my.showToast({
                            content: '删除失败'
                        });
                    }
                });

            }).catch(res => {
                console.log(res)
            })
    },
})